<?php
/**
 * Uploader Service
 * User: zng
 * Date: 2020/1/10
 * Time: 13:37
 * @package: app\admin\service\common
 */
namespace app\admin\service\common;

use app\exceptions\OrdinaryException;
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;
use think\File;

Class Uploader {

    /**
     * 七牛云配置
     * @var array
     */
    private $_config;

    public function __construct()
    {
        $this->_config = config('files.');
    }

    /**
     * 实例化Auth类
     */
    protected function auth()
    {
        return new Auth($this->_config['qiniu']['accessKey'], $this->_config['qiniu']['secretKey']);
    }

    /**
     * 文件上传
     * @param File $file 文件对象
     * @throws OrdinaryException
     */
    public function upload( File $file, string $type='image' )
    {
        $uploadManager = new UploadManager();
        $token = $this->uploadToken($type);
        list($res, $err) = $uploadManager->putFile(
            $token,
            $this->filename().'.'.pathinfo($file->getInfo('name'), PATHINFO_EXTENSION),
            $file->getPathname(),
            null,
            $file->getType());
        if ( $err !== null ) {
            throw new OrdinaryException('文件上传失败');
        }
        return $res['key'];
    }

    /**
     * 文件删除就是
     * @param string $key 文件名称
     *
     */
    public function delete(string $url)
    {
        $bucketManager = new BucketManager($this->auth());
        return $bucketManager->delete($this->_config['qiniu']['bucket'], ltrim(parse_url($url)['path'], '/'));
    }

    /**
     * 获取唯一标识
     * @return string|integer
     */
    private function filename()
    {
        list($s1,$s2)=explode(' ', microtime());
        return MD5(((float)sprintf('%.0f',(floatval($s1)+floatval($s2))*1000)).rand(1000,9999));
    }

    /**
     * 七牛云获取token
     *
     * @return string
     */
    public function uploadToken( string $type='image' )
    {
        $policy = $this->_config['qiniu']['policy'];
        $policy['mimeLimit'] = implode(';', $this->_config['mimeTypes'][$type]);
        return $this->auth()->uploadToken($this->_config['qiniu']['bucket'], null, 3600, $policy);
    }

}